import 'dart:async';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:number_pagination/number_pagination.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/eventbus/EventRefreshSupplier.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/views/dto/Supplier.dart';
import 'package:yuellyfactory/views/supplier/SupplierEditVC.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../util/ViewUtil.dart';

class SupplierVC extends StatefulWidget {
  const SupplierVC({super.key});

  @override
  State<SupplierVC> createState() => _SupplierVCState();
}

//列表页
class _SupplierVCState extends State<SupplierVC> {

  List datas=[];
  int currentPage=1;
  int totalPage=0;

  StreamSubscription? streamSubscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSupplierList();

    streamSubscription=eventBus.on<EventRefreshSupplier>().listen((event){
      currentPage=1;
      getSupplierList();
    });
  }

  @override
  void dispose() {
    if(streamSubscription!=null) {
      streamSubscription!.cancel();
    }

    super.dispose();
  }



  @override
  Widget build(BuildContext context) {


    return

      SingleChildScrollView(child:
      Column(
        children: [
          const SizedBox(height: 5,),
          Row(
            children: [
              const SizedBox(width: 20,),
              Text('供应商管理',style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,  fontSize: ViewUtil.fontSize(22)),),

              Expanded(child: Container()),
              ViewUtil.addIcon('新增供应商',(){
                Supplier supplier=Supplier();
                supplier.id="";

                showShadSheet(

                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  SupplierEditVC(
                    supplier: supplier,
                    callback: () {
                      //回调
                    },),
                );
              }),

            ],
          ),
          listView(),
          const SizedBox(height: 10,),
          Visibility(
              visible: totalPage>0,
              child: NumberPagination(

            controlButtonSize: const Size(30, 30),
            numberButtonSize: const Size(30, 30),
            onPageChanged: (int pageNumber) {
              //To optimize further, use a package that supports partial updates instead of setState (e.g. riverpod)
              setState(() {
                currentPage = pageNumber;
              });
            },
            visiblePagesCount: 5,
            totalPages: totalPage,
            currentPage: currentPage,
            // enableInteraction: false,
          ))
          ,
        ],
      ),);
  }

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }

  Widget listView(){
    final double tableHeight = _calculateTableHeight(datas.length);
    return // 表格（高度固定为计算值）
      Padding(
        padding: EdgeInsets.symmetric(horizontal: _outerPadding),
        child: Container(
          // 应用计算出的高度
          height: 600,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DataTable2(
            columnSpacing: 12,
            //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
            minWidth: 500,
            headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
            dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
            // 表头
            columns: const [
              DataColumn2(
                label: Text('  操作'),
                fixedWidth: 140,
              ),
              DataColumn2(
                label: Text('公司名称'),
                size: ColumnSize.L,

              ),
              DataColumn2(
                label: Text('联系人'),
                size: ColumnSize.L,
              ),
              DataColumn2(
                label: Text('联系电话'),
                size: ColumnSize.L,
              ),
            ],

            // 表格内容（行高固定）
            rows: datas.map((item) {
              return DataRow(cells: [
                DataCell(
                  Row(
                    children: [

                      ViewUtil.editIcon('编辑供应商',(){
                        showShadSheet(
                          side: ShadSheetSide.right,
                          context: context,
                          builder: (context) =>  SupplierEditVC(
                            supplier: item,
                            callback: () {
                              //回调
                            },),
                        );
                      }),

                      // ViewUtil.delIcon('删除供应商',(){
                      //
                      // }),

                    ],
                  ),
                ),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item.company),
                )),

                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item.name),
                )),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item.cellphone),
                )),

              ]);
            }).toList(),
          ),
        ),
      );
  }


  void getSupplierList(){

    BaseRequest.postHttp('supplier/list', parameters: {"pageSize":"10","page":'$currentPage'},
        canTip: true,
        context: context,
        onSuccess: (data) {
          bool result = BaseRequest.chekResponse(data, true);
          if (result) {

            dynamic records = data["data"]["records"];
            int total=data["data"]["pages"];
            totalPage=total;
            List allModel = [];
            for (var i = 0; i < records.length; i++) {
              var item = records[i];
              var part = Supplier.fromJson(item);
              allModel.add(part);
            }
            datas=allModel;
            setState(() {

            });
          }
        },
        onError: (error) {

        });
  }
}
